package com.xiyi.shouxin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.xiyi.shouxin.dao.admin.AdminRepository;
import com.xiyi.shouxin.dao.admin.RoleRepository;
import com.xiyi.shouxin.dao.user.PracticeRepository;
import com.xiyi.shouxin.dao.user.UserRepository;
import com.xiyi.shouxin.entity.admin.Admin;
import com.xiyi.shouxin.entity.admin.Role;
import com.xiyi.shouxin.entity.admin.mapper.AdminMapper;
import com.xiyi.shouxin.entity.admin.mapper.RoleMapper;
import com.xiyi.shouxin.entity.user.Practice;
import com.xiyi.shouxin.entity.user.User;
import com.xiyi.shouxin.entity.user.mapper.UserMapper;
import com.xiyi.shouxin.exception.CommonException;
import com.xiyi.shouxin.exception.ErrorCode;
import com.xiyi.shouxin.global.RoleEnum;
import com.xiyi.shouxin.view.pojo.AdminView;
import com.xiyi.shouxin.view.pojo.ItemPage;
import com.xiyi.shouxin.view.pojo.PracticeView;
import com.xiyi.shouxin.view.pojo.UserView;
import com.xiyi.shouxin.controller.pojo.RegisterParams;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private AdminRepository adminRepository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private PracticeRepository practiceRepository;

    /*
     * 用户列表
     */
    public ItemPage<UserView> findUserList(Long adminId, Long bindId, String keyword, Date startTime, Date endTime,
            int page,
            int size)
            throws Exception {
        List<UserView> list = new ArrayList<>();
        List<User> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");
        if (adminId != null) {
            Admin admin = adminRepository.findById(adminId, new AdminMapper());
            if (admin == null) {
                return new ItemPage<UserView>(list, total);
            }
            Role role = roleRepository.findById(admin.getRoleId(), new RoleMapper());
            if (role != null && RoleEnum.SUPER.getRole().equals(role.getRoleName())) {
                adminId = null;
            }
        }
        if (bindId != null) {
            adminId = bindId;
        }
        result = userRepository.findByMultiConditionsByPage(adminId, keyword, startTime, endTime, sort, page, size);
        total = userRepository.countByMultiConditions(adminId, keyword, startTime, endTime);

        for (User user : result) {
            list.add(new UserView(user, null, null));
        }
        return new ItemPage<UserView>(list, total);
    }



    /*
     * 用户批次练习列表
     */
    public ItemPage<UserView> findUserPracticeList(Long bindId, Long piciId, int page, int size)
            throws Exception {
        List<UserView> list = new ArrayList<>();
        List<User> result = new ArrayList<>();
        int total = 0;
        Sort sort = Sort.by(Direction.DESC, "id");
        result = userRepository.findByMultiConditionsByPage(bindId, null, null, null, sort, page, size);
        total = userRepository.countByMultiConditions(bindId, null, null, null);

        for (User user : result) {
            if (piciId != null) {
                Practice practice = practiceRepository.findByUserIdAndPiciId(user.getId(), piciId);
                if (practice != null) {

                    PracticeView view = new PracticeView(practice, null);
                    Integer tt = 0;
                    if (practice.getTotal() != null) {
                        tt = tt + practice.getTotal();
                    }
                    // if (practice.getNotReset() != null) {
                    // tt = tt + practice.getNotReset();
                    // }
                    view.setTotal(tt);
                    // Integer pass = 0;
                    // if (practice.getQualifiedQuantity() != null) {
                    // pass += practice.getQualifiedQuantity();
                    // }
                    // if (practice.getWeightNum() != null) {
                    // pass += practice.getWeightNum();
                    // }
                    // if (tt == 0) {
                    // view.setPassRate(0d);
                    // } else {
                    // BigDecimal dividend = new BigDecimal(pass.toString());
                    // BigDecimal divisor = new BigDecimal(tt);
                    // view.setPassRate(
                    // dividend.divide(divisor, 4, RoundingMode.HALF_UP).multiply(new
                    // BigDecimal(100))
                    // .doubleValue());
                    // }
                    list.add(new UserView(user, null, view));
                } else {
                    list.add(new UserView(user, null, null));
                }
            } else {
                list.add(new UserView(user, null, null));
            }

        }
        return new ItemPage<UserView>(list, total);
    }

    /*
     * 用户详情
     */
    public UserView findUser(Long userId) throws Exception {
        User user = userRepository.findById(userId, new UserMapper());
        if (user != null) {
            if (user.getAdminId() != null && user.getAdminId() > 0) {
                Admin admin = adminRepository.findById(user.getAdminId(), new AdminMapper());
                if (admin != null) {
                    return new UserView(user, new AdminView(admin, null), null);
                }
            }
            return new UserView(user, null, null);
        }
        throw new CommonException(ErrorCode.NOTFOUND);
    }

    /**
     * 通过手机查询用户
     */
    public User findUserByPhone(String phone) throws Exception {
        if (!org.springframework.util.StringUtils.hasText(phone)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        return userRepository.findByPhone(phone);
    }

    /*
     * 用户绑定
     */
    public void bindUser(Long userId, Long bindAdminId) throws Exception {
        if (userId == null || bindAdminId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        User update = new User();
        update.setAdminId(bindAdminId);
        userRepository.update(userId, update);
    }

    /*
     * 用户解绑
     */
    public void unbindUser(Long userId) throws Exception {
        if (userId == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        User update = new User();
        update.setAdminId(0L);
        userRepository.update(userId, update);
    }

    /*
     * 修改用户信息
     */
    public void updateUser(User user) throws Exception {
        if (user == null || user.getId() == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        if (Strings.isNotBlank(user.getStudentId())) {
            User stu = userRepository.findByStudentId(user.getStudentId());
            if (stu != null && !stu.getId().equals(user.getId())) {
                throw new CommonException(ErrorCode.ALREADYEXISTSStudent);
            }
        }
        User update = new User();
        update.setNickName(user.getNickName());
        update.setPhone(user.getPhone());
        update.setAvatar(user.getAvatar());
        update.setProvince(user.getProvince());
        update.setCity(user.getCity());
        update.setArea(user.getArea());
        update.setSex(user.getSex());
        update.setStudentId(user.getStudentId());
        update.setDeviceId(user.getDeviceId());
        update.setFeedback(user.getFeedback());
        userRepository.update(user.getId(), update);
    }

    /*
     * 用户绑定手机
     */
    public void bindUserPhone(Long userId, String phone) throws Exception {
        if (userId == null || !StringUtils.hasText(phone)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        User update = new User();
        update.setPhone(phone);
        userRepository.update(userId, update);
    }

    /*
     * 创建用户信息
     */
    public UserView createUser(String openid) throws Exception {
        if (openid == null || !StringUtils.hasText(openid)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        User user = new User();
        user.setOpenid(openid);
        user.setIsBind(0);
        user.setIsAnswer(0);
        user.setCreatedAt(new Date());
        user.setToken("");
        Long newId = userRepository.create(user);
        user.setId(newId);
        return new UserView(user, null, null);
    }

    /*
     * 根据openid查询用户
     */
    public UserView findUserByOpenid(String openid) throws Exception {
        User user = userRepository.findByOpenid(openid);
        if (user != null) {
            if (user.getAdminId() != null && user.getAdminId() > 0) {
                Admin admin = adminRepository.findById(user.getAdminId(), new AdminMapper());
                if (admin != null) {
                    return new UserView(user, new AdminView(admin, null), null);
                }
            }
            return new UserView(user, null, null);
        }
        return null;
    }

    /*
     * 生成token
     */
    public String generateTokenForUser(User user) {
        return "user_" + UUID.randomUUID().toString();
    }

    public void registerUser(RegisterParams params) throws Exception {
        // 检查手机号是否已注册
        User exist = userRepository.findByPhone(params.getPhone());
        if (exist != null) {
            throw new CommonException(ErrorCode.ALREADYEXISTS);
        }
        
        // 创建用户
        User user = new User();
        user.setPhone(params.getPhone());
        user.setNickName(params.getNickName());
        user.setAvatar(params.getAvatar());
        user.setSex(params.getSex());
        user.setAccount(params.getAccount());
        user.setStudentId(params.getStudentId());
        user.setProvince(params.getProvince());
        user.setCity(params.getCity());
        user.setArea(params.getArea());
        user.setCreatedAt(new java.util.Date());
        user.setIsBind(1);
        user.setIsAnswer(0);
        user.setToken("");
        
        // 密码加密
        String encryptedPassword;
        try {
            encryptedPassword = com.xiyi.shouxin.utils.MD5Util.MD5Encrypt(params.getPassword());
        } catch (Exception e) {
            throw new CommonException(ErrorCode.INTERNAL);
        }
        user.setPassword(encryptedPassword);
        
        // 创建用户记录
        Long userId = userRepository.create(user);
        user.setId(userId);
        
        // 创建对应的 admin 记录
        Admin admin = new Admin();
        admin.setNickName(params.getNickName());
        admin.setAccount(params.getAccount());
        admin.setPassword(encryptedPassword); // 使用相同的加密密码
        admin.setRoleId(2L); // 设置默认角色ID，根据你的业务需求调整
        admin.setIsDelete("1"); // 1表示开启状态
        
        Long adminId = adminRepository.create(admin);
        admin.setId(adminId);
        
        // 更新用户记录，绑定 adminId
        User updateUser = new User();
        updateUser.setAdminId(adminId);
        userRepository.update(userId, updateUser);
    }

    /**
     * 修改用户头像
     * @param userId
     * @param avatar
     * @throws Exception
     */
    public void updateUserAvatar(Long userId, String avatar) throws Exception {
        if (userId == null || !StringUtils.hasText(avatar)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        System.out.println("更新用户头像 - userId: " + userId + ", avatar: " + avatar);
        User update = new User();
        update.setAvatar(avatar);
        userRepository.update(userId, update);
        System.out.println("用户头像更新完成");
    }

    /**
     * 修改用户密码
     * @param userId
     * @param oldPassword
     * @param newPassword
     * @throws Exception
     */
    public void updateUserPassword(Long userId, String oldPassword, String newPassword) throws Exception {
        if (userId == null || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 获取当前用户信息
        User currentUser = userRepository.findById(userId, new UserMapper());
        if (currentUser == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 验证原密码
        String encryptedOldPassword;
        try {
            encryptedOldPassword = com.xiyi.shouxin.utils.MD5Util.MD5Encrypt(oldPassword);
        } catch (Exception e) {
            throw new CommonException(ErrorCode.INTERNAL);
        }
        
        if (!encryptedOldPassword.equals(currentUser.getPassword())) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 加密新密码
        String encryptedNewPassword;
        try {
            encryptedNewPassword = com.xiyi.shouxin.utils.MD5Util.MD5Encrypt(newPassword);
        } catch (Exception e) {
            throw new CommonException(ErrorCode.INTERNAL);
        }
        
        // 更新用户密码
        User update = new User();
        update.setPassword(encryptedNewPassword);
        userRepository.update(userId, update);
        
        // 同时更新对应的 admin 密码
        if (currentUser.getAdminId() != null && currentUser.getAdminId() > 0) {
            Admin updateAdmin = new Admin();
            updateAdmin.setPassword(encryptedNewPassword);
            adminRepository.update(currentUser.getAdminId(), updateAdmin);
        }
    }

    /**
     * 修改管理员头像
     * @param adminId
     * @param avatar
     * @throws Exception
     */
    public void updateAdminAvatar(Long adminId, String avatar) throws Exception {
        if (adminId == null || !StringUtils.hasText(avatar)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        Admin update = new Admin();
        update.setNickName(avatar); // 管理员使用 nickName 字段存储头像
        adminRepository.update(adminId, update);
    }

    /**
     * 修改管理员密码
     * @param adminId
     * @param oldPassword
     * @param newPassword
     * @throws Exception
     */
    public void updateAdminPassword(Long adminId, String oldPassword, String newPassword) throws Exception {
        if (adminId == null || !StringUtils.hasText(oldPassword) || !StringUtils.hasText(newPassword)) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 获取当前管理员信息
        Admin currentAdmin = adminRepository.findById(adminId, new AdminMapper());
        if (currentAdmin == null) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 验证原密码
        String encryptedOldPassword;
        try {
            encryptedOldPassword = com.xiyi.shouxin.utils.MD5Util.MD5Encrypt(oldPassword);
        } catch (Exception e) {
            throw new CommonException(ErrorCode.INTERNAL);
        }
        
        if (!encryptedOldPassword.equals(currentAdmin.getPassword())) {
            throw new CommonException(ErrorCode.INVALIDPARAMTER);
        }
        
        // 加密新密码
        String encryptedNewPassword;
        try {
            encryptedNewPassword = com.xiyi.shouxin.utils.MD5Util.MD5Encrypt(newPassword);
        } catch (Exception e) {
            throw new CommonException(ErrorCode.INTERNAL);
        }
        
        // 更新管理员密码
        Admin update = new Admin();
        update.setPassword(encryptedNewPassword);
        adminRepository.update(adminId, update);
    }

    public User findUserByAdminId(Long adminId) throws Exception {
        if (adminId == null) return null;
        return userRepository.findByAdminId(adminId);
    }

    public User getUserEntity(Long userId) throws Exception {
        if (userId == null) return null;
        return userRepository.findById(userId, new com.xiyi.shouxin.entity.user.mapper.UserMapper());
    }
}
